#!/bin/bash
# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2024 SteamFork (https://github.com/SteamFork)

# If we don't define a release type, assume it's a stable release.
if [ -n "${1}" ]
then
  RELEASE_TYPE="${1}"
else
  RELEASE_TYPE="rel"
fi

SCRIPT="$(realpath "${0}")"
IMAGE_DIR="${IMAGE_DIR}/${RELEASE_TYPE}/images"
WORK_DIR="${WORK_DIR}/image"

export IMAGE_DIR WORK_DIR

cat <<EOF
BUILD INFO:
===========================================================
SHELL: "${SHELL}"
BUILD_DIR: "${BUILD_DIR}"
BUILD_VER: "${BUILD_VER}"
RELEASE_TYPE: "${RELEASE_TYPE}"
INSTALLER_DIR: "${INSTALLER_DIR}"
OS_DIR: "${OS_DIR}"
SCRIPT_DIR: "${SCRIPT_DIR}"
WORK_DIR: "${WORK_DIR}"
IMAGE_DIR: "${IMAGE_DIR}"
REPO_DIR: "${REPO_DIR}"

EOF

# Builds are executed via automation using a minimal SteamFork installation.
if [ -f "/usr/bin/steamos-readonly" ]
then
  sudo steamos-readonly disable
fi

function cleanup() {
  sudo umount -R ${WORK_DIR}/buildwork/rootfs_mnt/var/cache/pacman/pkg \
	         ${WORK_DIR}/buildwork/rootfs_mnt ||:

  sudo rm -rf	${IMAGE_DIR} \
		${INSTALLER_DIR}/airootfs/etc/install.image \
		${INSTALLER_DIR}/airootfs/etc/pacman.conf \
		${INSTALLER_DIR}/airootfs/etc/pacman.d/steamfork-mirrorlist \
		${INSTALLER_DIR}/buildinfo \
		/tmp/buildinfo \
		${INSTALLER_DIR}/packages.x86_64 \
		${WORK_DIR}/image-build
}

# Clean up from any previous builds.
cleanup

# Import our keys
sudo pacman-key --add /usr/share/pacman/keyrings/steamfork.gpg

# Import the SteamOS keys
sudo pacman-key --add /usr/share/pacman/keyrings/holo.gpg

# Update cache
sudo pacman -Sy

# If we have an alternate package set, use it.
if [ -e "${INSTALLER_DIR}/package_lists/${RELEASE_TYPE}.x86_64" ]
then
  PACKAGESET="${RELEASE_TYPE}"
else
  PACKAGESET="full"
fi

cp -f ${INSTALLER_DIR}/package_lists/${PACKAGESET}.x86_64 ${INSTALLER_DIR}/packages.x86_64
sed -i 's~@STEAMOS_VERSION@~'${STEAMOS_VERSION}'~g' ${INSTALLER_DIR}/packages.x86_64

# Build the SteamFork image
sudo rootfs/steamfork/build-image --flavor ${RELEASE_TYPE} --deployment_rel ${RELEASE_TYPE} --upstream_ver "${STEAMOS_VERSION}" --snapshot_ver "${BUILD_VER}" --workdir "${WORK_DIR}" --output-dir "${IMAGE_DIR}" --add-release

# Prep for the installation image
source ${IMAGE_DIR}/latest_${RELEASE_TYPE}.releasemeta
sudo cp ${IMAGE_DIR}/latest_${RELEASE_TYPE}.releasemeta ${IMAGE_DIR}/buildinfo
sudo ln -sf ${IMAGE_DIR}/latest_${RELEASE_TYPE}.releasemeta /tmp/buildinfo
echo ${IMAGEFILE} | sudo tee ${IMAGE_DIR}/currentcandidate
${INSTALLER_DIR}/getlatestbuild.sh || exit 1


mkdir -p ${INSTALLER_DIR}/airootfs/etc/pacman.d
cp -f ${WORK_DIR}/buildwork/steamfork-mirrorlist ${INSTALLER_DIR}/airootfs/etc/pacman.d/

cp ${WORK_DIR}/buildwork/pacman.conf ${INSTALLER_DIR}/airootfs/etc/

# Build the installation image
sudo mkarchiso -v -w ${WORK_DIR}/image-build -o ${IMAGE_DIR}/installer ${INSTALLER_DIR}
